#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@fileName     : api.py
@description  : 
@time         : 2022年02月07日 17:24
@author       : WeiTingjun
@versions     : 1.0
'''
from flask import Flask, render_template, request, redirect, abort
from epwechat.message import WeCom
from todo_file import additional_save_todo, get_all_todos_with_format_spec, get_line, get_all_todos, cover_save_todos

app = Flask(__name__)


@app.route('/list')  # 所有待办页面
def get_todo_list():
    res = get_all_todos_with_format_spec()
    todo_list = res.get('todo_list')
    index = 0
    todo_dict = {}
    while index < len(todo_list):
        todo_dict[str(index + 1)] = todo_list[index]
        index = index + 1
    declare = res.get('format_specification').strip('#')  # 规则说明
    return render_template('list.html', res=todo_dict, declare=declare)


@app.route('/addPage')  # 新增待办页面
def get_add_page():
    return render_template('add.html')


@app.route('/add', methods=['post'])  # 增加待办
def add_todo():
    send_period = request.values.get('sendPeriod')
    send_time = request.values.get('sendTime')
    msg_title = request.values.get('messageTitle')
    msg_content = request.values.get('messageContent')
    msg_to_who = request.values.get('toWho')
    todo_list = []
    if msg_to_who:
        todo_str = '{}|{}|{}|{}|{}'.format(send_period, send_time, msg_title, msg_content, msg_to_who)
    else:
        todo_str = '{}|{}|{}|{}'.format(send_period, send_time, msg_title, msg_content)
    todo_list.append(todo_str)
    additional_save_todo(todo_list)
    return redirect('/list')


@app.route('/deletePage')  # 删除待办页面
def get_delete_page():
    return render_template('delete.html')


@app.route('/deleteTheLine', methods=['post'])  # 删除指定行
def delete_todo():
    line_num = int(request.values.get('lineNum'))
    if get_line(line_num + 1):
        todo_list = get_all_todos()
        todo_list.pop(line_num - 1)
        cover_save_todos(todo_list)
        return redirect('/list')
    else:
        abort(404)  # 行号不存在


@app.route('/sendMessage', methods=['post'])    # 调用接口发送消息
def send_msg():
    wc = WeCom()
    data = request.json
    title = data.get('messageTitle')
    content = data.get('messageContent')
    msgtype = data.get('messageType')
    if msgtype == 'textCard':
        wc.is_textcard_msg = True
    elif msgtype == 'text':
        wc.is_text_msg = True
    elif msgtype == 'markdown':
        wc.is_markdown_msg = True
    else:
        return '未指定消息类型，支持的消息类型：textCard、text、markdown'
    to_user = data.get('toUsers', None)
    wc.message.__setitem__('title', title)
    wc.message.__setitem__('detail', content)
    wc.send_msg(to_user)
    return 'success'


if __name__ == "__main__":
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=False
    )
